<?php
use Base\AdminController;
use Illuminate\Support\Str;
use JetBrains\PhpStorm\NoReturn;
use SimpleHtmlDom\ParseHtml;
use WeChat\Draft;
use WeChat\Freepublish;
use WeChat\Media;
use Yaf\Dispatcher;

/**
 * 图文管理
 */
class WechatArticleController extends AdminController
{
	protected string $table = 'wechat_articles';

    protected string $model = "WechatArticle";

	#[NoReturn] public function init(): void
    {
		if(Request::input("is_push")) {
			if(Request::input("is_push")<=1) {
				$this->where[] = ['is_push','=',Request::input("is_push")];
			}else {
				$this->where[] = ['is_push','>',Request::input("is_push")];
			}
		}
		if (Request::input("title")) {
            $this->where[] = ['title','like', '%'.Request::input("title").'%'];
        }
		parent::init();
    }

    #[NoReturn] public function pushAction():void
    {
        try {
            $config = Config::get("wechat");
            $wechat_config = ['appid'=>$config['AppId'],'appsecret'=>$config['AppSecret']];
            $wechat = new Freepublish($wechat_config);
            $info = WechatArticleModel::query()->where("id",Request::input("ids"))->first();
            $res = $wechat->submit($info['media_id']);
            WechatArticleModel::where("id",Request::input("ids"))->update([
                'is_push'=>1,
                'publish_id'=>$res['publish_id']
            ]);
            $this->apiSuccess([],"推送成功",20000);
        } catch (Exception $exception) {
            Log::$customFileName = LOG_PATH."/errors/";
            Log::error($exception->getMessage().$exception->getTraceAsString());
            $this->apiError($exception->getMessage());
        }
    }

    #[NoReturn] protected function update(): void
    {
        if (Request::instance()->isPost()||Request::instance()->isPut()) {
            try {
                $params = Request::all();
                $html = ParseHtml::str_get_html($params['content']);
                foreach($html->find("img") as $value) {
                    $src = $value->src;
                    $dataHref = $value->attr["data-href"];
                    $value->src = $dataHref;
                    $value->attr["data-href"] = $src;
                }
                $params['content'] = $html->save();
                $config = Config::get("wechat");
                $wechat_config = ['appid'=>$config['AppId'],'appsecret'=>$config['AppSecret']];
                $wechat = new Media($wechat_config);
                $path = str_replace([getRequestHost(),'/./'],'',$params['thumb_img']);
                $result = $wechat->addMaterial($path);
                $params['thumb_media_id'] = $result['media_id'];
                $params['updated_at'] = date("Y-m-d H:i:s");
                $this->cleanCache();
                $draft = new Draft($wechat_config);
                $articles = [
                    'thumb_media_id'=>$result['media_id'],
                    'content' => $params['content'],
                    'title' => $params['title'],
                ];
                if ($params['digest']) {
                    $articles['digest'] = $params['digest'];
                }
                if (isset($params['id'])) {
                    $info = WechatArticleModel::query()->where("id",$params['id'])->first();
                    if(isset($info['thumb_media_id'])) {
                        $wechat->delMaterial($info['thumb_media_id']);
                    }
                    if($info['media_id']) {
                        $draft->update($info['media_id'], 0, $articles);
                    }else {
                        $draftResult = $draft->add([$articles]);
                        $params['media_id'] = $draftResult['media_id'];
                    }
                    WechatArticleModel::where("id",$params['id'])->update($params);
                    $this->apiSuccess([],"更新成功",20000);
                }else {
                    $draftResult = $draft->add([$articles]);
                    $params['media_id'] = $draftResult['media_id'];
                    $params['created_at'] = date("Y-m-d H:i:s");
                    $params['uuid'] = (string)Str::uuid();
                    $params['user_id'] = $this->member_id;
                    $res = WechatArticleModel::insertGetId($params);
                    $info = WechatArticleModel::query()->where('id',$res)->first()->toArray();
                    $this->apiSuccess( $info,"新增成功",20000);
                }
            } catch (Exception $exception) {
                Log::$customFileName = LOG_PATH."/errors/";
                Log::error($exception->getMessage().$exception->getTraceAsString());
                $this->apiError($exception->getMessage());
            }
        }
    }

    #[NoReturn] protected function operate(): void
    {
        $info =  WechatArticleModel::query()->where('id',Request::input("ids"))->first()->toArray();
        if (!$info) $this->apiError("数据不存在");
        $html = ParseHtml::str_get_html($info['content']);
        foreach($html->find("img") as $value) {
            $src = $value->src;
            $dataHref = $value->attr["data-href"];
            $value->src = $dataHref;
            $value->attr["data-href"] = $src;
        }
        $info['content'] = $html->save();
        $this->apiSuccess($info,"success",20000);
    }

}
